import React, { useEffect, useState } from 'react';
import { NavItem } from '../../types';

import { Layout, Nav } from '@douyinfe/semi-ui';

import { getGlobalConfig } from '@ugeez/frontend-commons';
import { NavItemPropsWithItems } from '@douyinfe/semi-ui/lib/es/navigation';
import { action, observable } from 'mobx';
import { observer } from 'mobx-react';
import NavStore from '@admin/store/NavStore';
import { MainViewProps } from '.';

const useIcon = (IconClass) => {
    return <IconClass size="large" />;
}

const buildNavs = (items: NavItem[]) => {
    //{ itemKey: 'Home', text: '首页', icon: <IconHome size="large" /> },
    const navs: NavItemPropsWithItems[] = [];

    for (let item of items) {
        const navItem: NavItemPropsWithItems = {
            text: item.name,
            icon: item.icon ? useIcon(item.icon) : null,
            itemKey: item.key,
        };
        if (item.children && item.children.length > 0) {
            navItem.items = buildNavs(item.children);
        }

        navs.push(navItem);
    }

    return navs;
}

class LeftStore {

    @observable
    navs: NavItemPropsWithItems[] = [];

    navStore: NavStore;

    constructor(navStore: NavStore) {
        this.navStore = navStore;
        this.navs = buildNavs(navStore.items);
    }
}

const Left: React.FC<MainViewProps> = ({ navStore }): JSX.Element => {
    const [viewStore] = useState<LeftStore>(new LeftStore(navStore));

    const title = getGlobalConfig().setting.title;

    const { openNavKeys, selectedNavKeys } = navStore;
    const { navs } = viewStore;

    return <Layout.Sider
    // style={{ backgroundColor: 'var(--semi-color-bg-1)' }}
    >
        <Nav
            defaultSelectedKeys={['Home']}
            style={{ maxWidth: 220, height: '100%' }}
            items={navs}
            openKeys={openNavKeys}
            selectedKeys={selectedNavKeys}
            header={title ? {
                // logo: <img src="//lf1-cdn-tos.bytescm.com/obj/ttfe/ies/semi/webcast_logo.svg" />,
                text: title,
            } : null}
            footer={{
                collapseButton: true,
            }}
            onSelect={({ itemKey }) => {
                //触发导航
                navStore.navigate(itemKey as string);
            }}
            onOpenChange={({ itemKey, openKeys, isOpen }) => {
                //触发多级菜单显示/关闭
                navStore.toggleNav(itemKey as string, isOpen);
            }}
        />
    </Layout.Sider>
};

export default observer(Left);
